package com.gisuni.sddc.platformManager.service;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.gisuni.sddc.platformManager.dao.ProjectTypeDao;
import com.gisuni.sddc.platformManager.dao.RoleDao;
import com.gisuni.sddc.platformManager.model.PageInfo;
import com.gisuni.sddc.platformManager.model.ProjectType;
import com.gisuni.sddc.platformManager.model.ProjectTypeTimenode;
import com.gisuni.sddc.platformManager.model.Response;
import com.gisuni.sddc.platformManager.model.RoleInfo;
import com.gisuni.sddc.platformManager.model.RoleRModule;
import com.gisuni.sddc.platformManager.model.RoleRResource;
import com.gisuni.sddc.platformManager.model.Tree;
import com.gisuni.sddc.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

@IocBean
public class ProjectTypeService   {

	private Log log = Logs.getLog(ProjectTypeService.class);    
    @Inject
    private ProjectTypeDao projectTypeDao;
  
    public void findDataGrid(PageInfo pageInfo) {
//        pageInfo.setRows(roleMapper.findRolePageCondition(pageInfo));
//        pageInfo.setTotal(roleMapper.findRolePageCount(pageInfo));
    }

  
    public List<Tree> findTree(String flag) {
        List<Tree> trees = new ArrayList<Tree>();
        String sql = "select t.id,t.project_type_name from SDDCGISPLATFORM.project_type t where 1=1";
        if(!StringUtil.isNullOrEmpty(flag)){
        	sql+=" and flag = '"+flag+"'";
        }
        
        List<ProjectType> roles = projectTypeDao.findEntity(sql);
//        Tree root = new Tree();
//        trees.add(root);
        for (ProjectType role : roles) {
            Tree tree = new Tree();
            tree.setId(role.getId());
            tree.setText(role.getProjectTypeName());
            tree.setPid("0");
            trees.add(tree);
        }
        return trees;
    }

  
    public Response deleteEntityById(String id) {
   	 Response res = new Response();
   	 res.setSuccess(false);
   	 try{
   		//如果有项目已关联项目类型,则无法删除
   		String sql = "select * from PROJECT_R_TIMENODE where PROJECT_TYPE_ID='"+id+"'";
   		String check = projectTypeDao.querySql(sql);
   		if(!"[]".equals(check)){
	       	 res.setSuccess(false);
	       	 res.setMsg("1");
	       	 return res;
   		}
   		
   		String delProjectType = " delete from PROJECT_TYPE where ID = '"+id+"'";
   		String delProjectTypeTImeNode = " delete from PROJECT_TYPE_TIMENODE where PROJECT_TYPE_ID ='"+id+"'";
 
    	projectTypeDao.executeSQL(delProjectTypeTImeNode);
    	projectTypeDao.executeSQL(delProjectType);
    	 
    	res.setSuccess(true);
    	return res;
   	 }catch(Exception e){
   		 e.printStackTrace();
   		 log.error(e);
   		 res.setMsg("操作失败");
   		 return res;
   	 }
    }
    
  
    public String findEntityById(String id) {
    	String sql = "select * from project_type t left join project_type_timenode t1 on t.id=t1.project_type_id where t.id='"+id+"' order by t1.timenode_index";
        return projectTypeDao.querySql(sql);
    }


	public Response addEntity(HttpServletRequest request) throws Exception{
   	 Response res = new Response();
   	 res.setSuccess(false);
   	 String[] nodeNames = request.getParameterValues("timeNodeName");
     String[] cicles = request.getParameterValues("circle");
   	 String projectTypeName = request.getParameter("projectTypeName");
   	 String flag = request.getParameter("flag");//类型  "DQXM"短期项目    "ZCQXM" 中长期项目  "ZSJWSXM"  在售及未售项目  "CYXZ"  产业小镇   //"WYTZ" 外业拓展  
   	 
   	 List list = checkData(nodeNames,cicles,projectTypeName);
     
   	 
   	 
   	 if(list==null || list.size()==0){
 	   	  res.setMsg("输入格式有误,请重新填写");
 	   	  return res ; 
   	 }
   	 
   	 for(String node:nodeNames){
    	 if(node.length()>50){
    		 res.setMsg(node+"超出限制的50个字符");
    		 return res ; 
    	 }
   	 }
   	 
	 String id = UUID.randomUUID().toString().replaceAll("-", "");
	 ProjectType entity = new ProjectType();
	 entity.setId(id);
	 entity.setProjectTypeName(projectTypeName);
	 entity.setCreateTime(new Date());
	 entity.setUpdateTime(new Date());
	 entity.setFlag(flag);
	 ProjectType tProjectType = projectTypeDao.addProjectType(entity);
	 
	 if(tProjectType!=null){
	     for(int i = 0 ; i<list.size() ; i++){
	    	 String[] data =  ((String)list.get(i)).split("-v-");
	    	 String nodeName= data[0];
	    	 String cicle= data[1];
	    	 ProjectTypeTimenode node = new ProjectTypeTimenode();
	    	 node.setProjectTypeId(id);//项目类型ID
	    	 node.setTimenodeCycle(Integer.parseInt(cicle));//周期
	    	 node.setTimenodeIndex(i+1);//序号
	    	 node.setTimenodeName(nodeName);//名称
	    	 node.setId(UUID.randomUUID().toString().replaceAll("-", ""));
	    	 
	    	 projectTypeDao.addProjectTypeTimenode(node);
	     }
	 }else{
  	   	  res.setMsg("保存项目类型失败,请稍后重试");
  	   	  return res ; 
	 }
     	res.setSuccess(true);
		return res;
	}

	

	public Response updateEntity(HttpServletRequest request) throws Exception{
	   
		 Response res = new Response();
	   	 res.setSuccess(false);
	   	 String[] nodeNames = request.getParameterValues("timeNodeName");
	     String[] cicles = request.getParameterValues("circle");
	   	 String projectTypeName = request.getParameter("projectTypeName");
	   	 String oldProjectTypeName = request.getParameter("oldProjectTypeName");
	   	 String projectTypeId = request.getParameter("projectTypeId");
	   	 String timeNodeSize = request.getParameter("timeNodeSize");
	   	 String flag = request.getParameter("flag");//类型  "0"短期项目    "1" 中长期项目  "2"  在售及未售项目  "3"  产业小镇    "4" 外业拓展
	   	 String oldFlag = request.getParameter("oldFlag");//原类型  "0"短期项目    "1" 中长期项目  "2"  在售及未售项目  "3"  产业小镇  "4' 外业拓展
	   	 List list = checkData(nodeNames,cicles,projectTypeName);
	     
	   	 if(list==null || list.size()==0){
	 	   	  res.setMsg("输入格式有误,请重新填写");
	 	   	  return res ; 
	   	 }
	   	 for(String node:nodeNames){
	    	 if(node.length()>50){
	    		 res.setMsg(node+"超出限制的50个字符");
	    		 return res ; 
	    	 }
	   	 }
	   	 //名称有改变则更新
	   	 if(!oldProjectTypeName.equals(projectTypeName)||!flag.equals(oldFlag)){
	   		  projectTypeDao.executeSQL("update SDDCGISPLATFORM.PROJECT_TYPE set PROJECT_TYPE_NAME = '"+projectTypeName+"',FLAG='"+flag+"',UPDATE_TIME=sysdate where ID ='"+projectTypeId+"'");
	   		 
	   	 }
	   	 // 
	     for(int i = 0 ; i<list.size() ; i++){
	    	 String[] data =  ((String)list.get(i)).split("-v-");
	    	 String nodeName= data[0];
	    	 String cycle= data[1];
	    	 String sql = "update SDDCGISPLATFORM.PROJECT_TYPE_TIMENODE set TIMENODE_NAME='"+nodeName+"', TIMENODE_CYCLE="+cycle+" where PROJECT_TYPE_ID = '"+projectTypeId+"' and TIMENODE_INDEX="+(i+1);
	    	 projectTypeDao.executeSQL(sql);
//	    	 ProjectTypeTimenode node = new ProjectTypeTimenode();
//	    	 node.setProjectTypeId(projectTypeId);//项目类型ID
//	    	 node.setTimenodeCycle(Integer.parseInt(cicle));//周期
//	    	 node.setTimenodeIndex(i);//序号
//	    	 node.setTimenodeName(nodeName);//名称
//	    	 String id = UUID.randomUUID().toString().replaceAll("-", "");
//	    	 node.setId(id);
//	    	 projectTypeDao.addProjectTypeTimenode(node);
	     }
	     
	     //增加/删除去掉的节点
    	 String executeSQL = null ; 
    	 int oldNodeSize = Integer.parseInt(timeNodeSize);
	     if(Integer.parseInt(timeNodeSize)<list.size()){
	    	 for(int i = 0 ;i<list.size()-oldNodeSize;i++){
		    	 String[] data =  ((String)list.get(oldNodeSize+i)).split("-v-");
		    	 String nodeName= data[0];
		    	 String cycle= data[1];
		    	 ProjectTypeTimenode node = new ProjectTypeTimenode();
		    	 node.setProjectTypeId(projectTypeId);//项目类型ID
		    	 node.setTimenodeCycle(Integer.parseInt(cycle));//周期
		    	 node.setTimenodeIndex(oldNodeSize+i+1);//序号
		    	 node.setTimenodeName(nodeName);//名称
		    	 node.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		    	 projectTypeDao.addProjectTypeTimenode(node);
	    	 }
	     }else{
	    	 executeSQL= "delete from SDDCGISPLATFORM.PROJECT_TYPE_TIMENODE where PROJECT_TYPE_ID = '"+projectTypeId+"' and TIMENODE_INDEX>"+list.size();
	    	 projectTypeDao.executeSQL(executeSQL);
	     }

	     res.setSuccess(true);
		return res;
	}
	

	private List checkData(String[] nodeNames,String[] cycles,String projectTypeName){
	     //校验
	     boolean flag = true  ;
	     if(StringUtil.isNullOrEmpty(projectTypeName)){
//	    	  res.setMsg("项目类型名称不能为空");
	    	 return null ; 
	     }
	     
	     if(nodeNames==null || nodeNames.length==0){
//	   	   res.setMsg("节点名称不能为空");
	   	   return null ; 
	     }
	     
	     if(cycles==null || cycles.length==0){
//	     	   res.setMsg("周期不能为空");
	     	   return null ; 
	     }
	     
	     flag = checkProjectTypeData(nodeNames);
	     if(!flag){
//		   	  res.setMsg("格式不符合标准");
		   	  return null ; 
	     }
	     
	     flag = checkProjectTypeData(cycles);
	     if(!flag){
//		   	  res.setMsg("格式不符合标准");
		   	  return null ; 
	     }
		
	     List list = new ArrayList();
	     
	     //再次校验
	     for(int i = 0 ; i<nodeNames.length ; i++){
	    	 String nodeName= nodeNames[i];
	    	 String cicle= cycles[i];
	    	 if(StringUtil.isNullOrEmpty(nodeName)){
	    		 break;
	    	 }
	    	 if(StringUtil.isNullOrEmpty(cicle)){
//		   	   	  res.setMsg(nodeName+"的周期不能为空");
		   	   	  return null ; 
	    	 }
	    	 list.add(nodeName+"-v-"+cicle);
	     }
	     return list;
	}
 
	private boolean checkProjectTypeData(String[] params) {
		 if(params==null ||params.length==0){
			 return false;
		 }
		 //TODO
//		 for(int i = 0 ; i<params.length ; i++){
//			 String p = params[i];
//			 if(StringUtil.isNullOrEmpty(p));
//		 }
		
		return true;
	}


	//没做分页
	public Response queryBaseEntityAll(int from, int to, String typeName,String area) {
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
		try {
 
			StringBuffer sbfSQL =  new StringBuffer(" select t.id,t.project_type_name,t.flag, t1.timenode_index,t1.timenode_name||'; ' detail from PROJECT_TYPE t" 
					 +" left join PROJECT_TYPE_TIMENODE t1 on t.id=t1.project_type_id where 1=1 ");
			
			if(!StringUtil.isNullOrEmpty(typeName)){
				sbfSQL.append(" and t.project_type_name like '%"+typeName.trim()+"%' ");
			}
			
			if(!StringUtil.isNullOrEmpty(area)){
				sbfSQL.append(" and t.project_type_area like '%"+area.trim()+"%' ");
			}
			//根据类型名称,节点顺序排序
			sbfSQL.append(" order by t.project_type_name,t1.project_type_id,t1.timenode_index ");
			String result = projectTypeDao.queryBaseEntityAll(  from,  to, sbfSQL.toString());
			
			if(!StringUtil.isNullOrEmpty(result)){
				JSONArray dataJsonArr = new JSONArray(result);
				JSONArray resultJsonArr = new JSONArray();
				JSONObject resultOBJ = new JSONObject();
				 
				String projectTypeName = null; //项目类型名称
				StringBuffer detailSbf = new StringBuffer();
			
				for(int i=0;i<dataJsonArr.length();i++){
					JSONObject obj = (JSONObject)dataJsonArr.get(i);
					Iterator iterator = obj.keys();
					boolean addDetailflag = true;//是否追加明细值
					String detail = "";//明细值
					String areaName = "";//所属区域
					String typeFlag = "";//项目分类
					String id = "";//ID
					while (iterator.hasNext()) {
						String key = (String) iterator.next();
						
						if(key.equals("TIMENODE_INDEX")){//
							
						}else if(key.equals("DETAIL")){ //节点明细
							detail = (String)obj.getString("DETAIL");
						}else if(key.equals("ID")){ //节点明细
							id = (String)obj.getString("ID");
						}else if(key.equals("PROJECT_TYPE_NAME")){ //类型名称
							if(projectTypeName==null){
								projectTypeName = (String) obj.get("PROJECT_TYPE_NAME");
							}else if(!projectTypeName.equals(obj.get("PROJECT_TYPE_NAME"))){ //下一个项目类型
								projectTypeName = (String) obj.get("PROJECT_TYPE_NAME");
								addDetailflag =false; 
							} 
						}else if(key.equals("PROJECT_TYPE_AREA")){ //所属区域
							areaName = (String)obj.getString("PROJECT_TYPE_AREA");
						}else if(key.equals("FLAG")){ //项目分类
							typeFlag = (String)obj.getString("FLAG");
						}
					}
					
					if(!addDetailflag){
						resultOBJ.put("DETAIL", detailSbf.toString());
						resultJsonArr.put(resultOBJ);
						detailSbf = new StringBuffer();
						resultOBJ = new JSONObject();
					} 
					
					if(i==dataJsonArr.length()-1){
						detailSbf.append(detail);
						resultOBJ.put("DETAIL", detailSbf.toString());
						resultJsonArr.put(resultOBJ);
					}
					resultOBJ.put("PROJECT_TYPE_NAME", projectTypeName);
					resultOBJ.put("PROJECT_TYPE_AREA", areaName);
					resultOBJ.put("ID", id);
					resultOBJ.put("FLAG", typeFlag);
					detailSbf.append(detail);
				}
				response.setResult(resultJsonArr.toString());
				
				return response;
			}else{
				response.setResult("");
			}
			
			response.setSuccess(true);
			return response;
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			response.setMsg("查询失败");
			return response;
		}
		
	}


	public String getPrivilegeByRoleId(String id) {
		StringBuffer resultSbf = new StringBuffer();
		if(!StringUtil.isNullOrEmpty(id)){
			//加了c就必然有一条数据 
			String findModuleIdSql = "select 'c,'||wm_concat(t.module_id) ids from role_r_module t where role_id = '"+id+"'";
			String findResourceIdSql = "select 'c,'||wm_concat(t.resource_id) ids from role_r_resource t where role_id = '"+id+"'";
			
			String moduleResult = projectTypeDao.querySql(findModuleIdSql);
			String m = jsonToString(moduleResult,"IDS");
			if(!StringUtil.isNullOrEmpty(m)){
				resultSbf.append(m);
			}
			
			String resourceResult = projectTypeDao.querySql(findResourceIdSql);
			resultSbf.append("|");
			m = jsonToString(resourceResult,"IDS");
			if(!StringUtil.isNullOrEmpty(m)){
				resultSbf.append(m);
			}
		}
		
		return resultSbf.toString();
	}
	
	public String jsonToString(String json ,String name){
		
		JSONArray resultJsonArr = new JSONArray(json);
		StringBuffer sbf = new StringBuffer();
		if (resultJsonArr != null && resultJsonArr.length() > 0) {
			for (int i = 0; i < resultJsonArr.length(); i++) {
				JSONObject ret = (JSONObject) resultJsonArr.get(i);
				Iterator iterator = ret.keys();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					 
					if(name.equals(key)){
						String value = (String) ret.get(key);
						sbf.append(value);
					}
				}	
			}
		}
//		System.out.println(sbf.toString());
		return sbf.toString();
		
	}


	public String getAllTypeTimeNode() {
		String sql = "select t1.ID,t1.Timenode_Name,t.Project_Type_Name from project_type t left join project_type_timenode t1 on t.id = t1.project_type_id order by t.Project_Type_Name";
        return projectTypeDao.querySql(sql);
	}
     
	public String getTimeNodeByTypeId(String id) {
		String sql = "select t1.ID,t1.Timenode_Name,t.Project_Type_Name from project_type t left join project_type_timenode t1 on t.id = t1.project_type_id where t.id='"+id+"'";
		System.out.println(sql);
	       return projectTypeDao.querySql(sql);
	}


	public String getZCQXMBelongInfo(String table) {
		String sql="select t.FQMC,t.CSGS,t.CSMC from "+table+" t group by t.FQMC,t.CSMC,t.CSGS order by t.CSGS";
		System.out.println(sql);
		return projectTypeDao.querySql(sql);
	}
 
 

}
